package com.cgbl.cg.vm.mine

import android.app.Application
import androidx.databinding.ObservableField
import api.UserServiceFactory
import com.blankj.utilcode.util.StringUtils
import com.cgbl.cg.R
import com.robot.base.base.vm.GLBaseViewModel
import com.robot.base.common.api.AbstractViewModelSubscriber
import com.robot.base.util.ToastUtils
import me.goldze.mvvmhabit.binding.command.BindingAction
import me.goldze.mvvmhabit.binding.command.BindingCommand
import me.goldze.mvvmhabit.http.BaseResponse

class ModifyAccountViewModel(application: Application) : GLBaseViewModel(application) {

    val oldPassword = ObservableField("")
    val newPassword = ObservableField("")

    val confirmCommand = BindingCommand<Any>(BindingAction {
        updatePassword()
    })

    fun updatePassword() {
        if ((oldPassword.get()?.length ?: 0) < 8 || (oldPassword.get()?.length ?: 0) > 18) {
            ToastUtils.showShort(StringUtils.getString(R.string.app_error_8))
            return
        }
        if ((newPassword.get()?.length ?: 0) < 8 || (newPassword.get()?.length ?: 0) > 18) {
            ToastUtils.showShort(StringUtils.getString(R.string.app_error_8))
            return
        }
        showLoadingDialog()
        UserServiceFactory.updatePassword(
            mapOf(
                "oldPassword" to oldPassword.get(),
                "password" to newPassword.get()
            )
        ).subscribe(object : AbstractViewModelSubscriber<BaseResponse<String>>(this) {
            override fun onNext(t: BaseResponse<String>) {
                dismissLoadingDialog()
                ToastUtils.showShort(t.msg)
                finish()
            }
        })
    }
}